<script setup>
import { ElMessage } from 'element-plus'
import { ref, reactive, getCurrentInstance, nextTick, onMounted, onUnmounted } from 'vue'
const { proxy } = getCurrentInstance()
import { MdPreview, MdCatalog } from 'md-editor-v3'
import 'md-editor-v3/lib/style.css'

const formData = ref({})
const messageList = ref([])
const loading = ref(false)

// 是否发送消息
const keySend = (event) => {
  if (!(event.ctrlKey && event.key === 'Enter')) {
    return
  }
  sendMessage()
}

// 发送消息
const sendMessage = () => {
  const message = formData.value.content
  if (!message) {
    ElMessage({
      type: 'warning',
      message: '请输入内容',
      duration: 2000,
    })
    return
  }
  messageList.value.push({
    type: 0, // 消息类型为0 表示是我们自己发送的消息
    content: message,
  })

  messageList.value.push({
    type: 1, // 消息类型为1 表示是后台返回的消息
    content: [],
    loading: true,
  })

  // 开始加载
  loading.value = true

  // 发送
  const eventSource = new EventSource(`/api/user/ai/stream?message=${message}`)

  // 清空表单
  formData.value.content = ''

  eventSource.onmessage = (event) => {
    let response = event.data
    console.log(response)
    if (response == 'end') {
      close()
      return
    }

    // 字符串转json
    response = JSON.parse(response).content

    // 显示到页面（push到数组中最后一个元素）
    messageList.value[messageList.value.length - 1].content.push(response)

    //滚动到底部
    nextTick(() => {
      const content = document.getElementById('message-panel')
      content.scrollTop = content.scrollHeight
    })
  }

  eventSource.onerror = (error) => {
    close()
  }

  const close = () => {
    eventSource.close()
    messageList.value[messageList.value.length - 1].loading = false
    loading.value = false
  }
}
</script>

<template>
  <div class="chat-panel">
    <div class="chat-title">AI问答</div>
    <div class="message-panel" id="message-panel">
      <div class="message-list">
        <div :class="['message-item', item.type == 1 ? 'ai-item' : '']" v-for="(item, index) in messageList"
          :id="'item' + index">
          <template v-if="item.type == 0">
            <div class="message-content">
              <div class="content-inner user-item">{{ item.content }}</div>
            </div>
            <!-- <div class="user-icon">
              我
            </div> -->
          </template>
          <template v-else>
            <div class="ai-icon">
              AI
            </div>
            <div class="message-content ai-item">
              <MdPreview previewTheme="vuepress" :codeFoldable="false" editorId="preview"
                :modelValue="item.content.join('')" />
              <!-- <div class="loading" v-if="item.loading">
                <img src="../assets/loading.gif">
              </div> -->
            </div>
          </template>
        </div>
      </div>

      <div class="send-panel">
        <el-form :model="formData" ref="formDataRef" @submit.prevent>
          <!--input输入-->
          <el-form-item label="" prop="content" style="margin-bottom: 5px;">
            <el-input type="textarea" :rows="3" clearable placeholder="请输入你想问的问题" v-model="formData.content"
              @keyup="keySend"></el-input>
          </el-form-item>
          <!--input输入-->
          <el-form-item label="" prop="" class="send-btn">
            <el-button type="primary" @click="sendMessage" :disabled="loading">发送(ctrl+enter)</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<style scoped>
.chat-panel {
  background: #eff0f6;
  width: 100%;
  height: 100%;
  border-radius: 20px;
  padding-bottom: 170px;
}

.chat-panel .chat-title {
  padding-top: 10px;
  padding-bottom: 10px;
  text-align: center;
  font-size: 20px;
  font-weight: bold;
}

.chat-panel .message-panel {
  position: relative;
  height: 100%;
  overflow: auto;
  padding-bottom: 10px;
}

.chat-panel .message-panel .message-list {
  margin: 0px auto;
  width: 100%;
}

.chat-panel .message-panel .message-list .message-item {
  margin: 10px 0px;
  display: flex;
}

.chat-panel .message-panel .message-list .message-item .user-icon {
  margin-right: 10px;
}

.chat-panel .message-panel .message-list .message-item .user-icon,
.chat-panel .message-panel .message-list .message-item .ai-icon {
  width: 40px;
  height: 40px;
  line-height: 40px;
  border-radius: 20px;
  background: #535353;
  color: #fff;
  text-align: center;
  margin-left: 10px;
}

.chat-panel .message-panel .message-list .message-item .ai-icon {
  background: #64018f;
}

.chat-panel .message-panel .message-list .message-item .message-content {
  flex: 1;
  margin-left: 10px;
  margin-right: 10px;
  align-items: center;
  display: flex;
  justify-content: flex-end;
}

.chat-panel .message-panel .message-list .message-item .content-inner {
  background: #2d65f7;
  border-radius: 5px;
  padding: 10px;
  color: #fff;
}

.chat-panel .message-panel .message-list .user-item {
  margin-left: 50px;
}

.chat-panel .message-panel .message-list .ai-item {
  line-height: 23px;
  margin-right: 0px;
}

.chat-panel .message-panel .message-list .ai-item .message-content {
  display: block;
  background: #fff;
  border-radius: 5px;
}

.chat-panel .message-panel .message-list .ai-item .user-icon {
  background: #64018f;
  margin-left: 0px;
}

.chat-panel .message-panel .message-list .ai-item :deep(.md-editor-previewOnly) {
  border-radius: 5px;
  background: #fff;
}

.chat-panel .message-panel .message-list .ai-item :deep(.md-editor-preview-wrapper) {
  padding: 10px;
}

.chat-panel .message-panel .message-list .ai-item .loading {
  text-align: center;
}

.chat-panel .send-panel {
  position: fixed;
  bottom: 0;
  margin: 5px auto 0px;
  width: 700px;
  border-radius: 5px;
  padding: 20px;
  background: #eff0f6;
  z-index: 1;
}

.chat-panel .send-panel .send-btn {
  text-align: right;
  margin-bottom: 15px;
  padding: 5px;
}

.chat-panel .send-panel .send-btn :deep(.el-form-item__content) {
  justify-content: flex-end;
}

.chat-panel .send-panel :deep(.el-textarea__inner) {
  border: 0 !important;
  resize: none !important;
  box-shadow: none;
}

.no-data {
  text-align: center;
  color: #5f5f5f;
}
</style>
